package com.tiheima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tiheima.mapper.StudentMapper;
import com.tiheima.model.dos.StuListDO;
import com.tiheima.model.dto.student.StuAddDTO;
import com.tiheima.model.dto.student.StuPageQuery;
import com.tiheima.model.dto.student.StuUpdataDTO;
import com.tiheima.model.result.PageResult;
import com.tiheima.model.vo.GetStuByIdVO;
import com.tiheima.service.StudentService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Override
    public PageResult<StuListDO> page(StuPageQuery query) {
        query.checkPageParam();
        PageHelper.startPage(query.getPage(), query.getPageSize());
        List<StuListDO> list = studentMapper.pageList(query);
        PageInfo<StuListDO> pageResult = new PageInfo<>(list);

        return PageResult.of(pageResult.getTotal(), pageResult.getList());
    }

    @Transactional
    @Override
    public void deleteStu(ArrayList<String> ids) {
        if (ids.isEmpty()) {
            throw new RuntimeException("id不能为空");
        }
        studentMapper.deleteStu(ids);
    }

    @Transactional
    @Override
    public void addStu(StuAddDTO stuAddDTO) {
        stuAddDTO.setCreateTime(LocalDateTime.now());
        stuAddDTO.setUpdateTime(LocalDateTime.now());
        if (BeanUtil.hasNullField(stuAddDTO, "degree", "clazzId", "address", "graduationDate")) {
            throw new RuntimeException("参数非法");
        }
        studentMapper.addStu(stuAddDTO);
    }

    @Transactional
    @Override
    public GetStuByIdVO getStuById(Integer id) {
        if (id == null) {
            throw new RuntimeException("id不能为空");
        }
        return studentMapper.getStuById(id);
    }

    @Override
    public void updateStu(StuUpdataDTO stuUpdataDTO) {
        stuUpdataDTO.setUpdateTime(LocalDateTime.now());
        if (BeanUtil.hasNullField(stuUpdataDTO, "degree", "clazzId", "address", "graduationDate")) {
            throw new RuntimeException("参数非法");
        }
        studentMapper.updateStu(stuUpdataDTO);
    }

    @Override
    public void violation(Integer id, Integer score) {
        if (id == null || score == null) {
            throw new RuntimeException("id或分数不能为空");
        }
        studentMapper.violation(id, score);
    }


}
